from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from models.user import User
from extensions import db

user_bp = Blueprint('user', __name__)

@user_bp.route('/users')
@login_required
def user_list():
    # 获取查询参数
    username = request.args.get('username', '')
    email = request.args.get('email', '')
    role = request.args.get('role', '')
    status = request.args.get('status', '')
    
    # 构建查询
    query = User.query
    if username:
        query = query.filter(User.username.like(f'%{username}%'))
    if email:
        query = query.filter(User.email.like(f'%{email}%'))
    if role:
        query = query.filter(User.role == role)
    if status:
        query = query.filter(User.status == (status == 'true'))
    
    # 分页
    page = request.args.get('page', 1, type=int)
    per_page = 10  # 每页显示10条记录
    pagination = query.order_by(User.created_at.desc()).paginate(
        page=page, per_page=per_page, error_out=False)
    users = pagination.items
    
    # 角色选项
    role_choices = [
        ('', '所有角色'),
        ('researcher', '科研人员'),
        ('logistics', '物流人员'),
        ('finance', '财务人员'),
        ('service', '售后服务人员')
    ]
    
    return render_template('user/list.html', 
                         users=users, 
                         pagination=pagination,
                         role_choices=role_choices,
                         username=username,
                         email=email,
                         role=role,
                         status=status)

@user_bp.route('/users/add', methods=['GET', 'POST'])
@login_required
def user_add():
    if request.method == 'POST':
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')
        role = request.form.get('role')
        
        if User.query.filter_by(username=username).first():
            flash('用户名已存在', 'error')
            return redirect(url_for('user.user_add'))
            
        if User.query.filter_by(email=email).first():
            flash('邮箱已存在', 'error')
            return redirect(url_for('user.user_add'))
            
        user = User(username=username, email=email, role=role)
        user.set_password(password)
        
        db.session.add(user)
        db.session.commit()
        
        flash('用户添加成功', 'success')
        return redirect(url_for('user.user_list'))
        
    return render_template('user/add.html')

@user_bp.route('/users/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def user_edit(id):
    user = User.query.get_or_404(id)
    
    if request.method == 'POST':
        email = request.form.get('email')
        role = request.form.get('role')
        status = request.form.get('status') == 'on'
        
        if email != user.email and User.query.filter_by(email=email).first():
            flash('邮箱已存在', 'error')
            return redirect(url_for('user.user_edit', id=id))
            
        user.email = email
        user.role = role
        user.status = status
        
        if request.form.get('password'):
            user.set_password(request.form.get('password'))
            
        db.session.commit()
        flash('用户更新成功', 'success')
        return redirect(url_for('user.user_list'))
        
    return render_template('user/edit.html', user=user)

@user_bp.route('/users/delete/<int:id>')
@login_required
def user_delete(id):
    user = User.query.get_or_404(id)
    if user.id == current_user.id:
        flash('不能删除当前登录用户', 'error')
        return redirect(url_for('user.user_list'))
        
    db.session.delete(user)
    db.session.commit()
    flash('用户删除成功', 'success')
    return redirect(url_for('user.user_list')) 